package com.read.controller;

import com.read.common.R;
import com.read.config.AliyunOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;

@RestController
@RequestMapping("/upload")
@Api(tags = "图片上传_视频上传_文件上传_徐成龙")
public class OssController {

    @Autowired
    private AliyunOssUtil ossUtil;

    String upload = null;

    @PostMapping("/uploadFile")
    @ApiOperation("视频上传_返回一个url地址给前端(记得把提交的时候把地址传过来哦!)")
    public R upload(@RequestParam("file") MultipartFile file) {
        System.out.println(file.getOriginalFilename() + "---------");
        try {
            if (file != null) {
                String fileName = file.getOriginalFilename();
                if (!"".equals(fileName.trim())) {
                    File newFile = new File(fileName);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    //把file里的内容复制到newFile中
                    file.transferTo(newFile);
                    upload = ossUtil.upload(newFile);
                    //图片回显地址:
                    System.out.println("path=" + upload);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (upload != "" || upload != null) {
            String uploadurl = "https://xcl-yxy.oss-cn-hangzhou.aliyuncs.com/" + upload;
            return R.ok().data("uploadurl", uploadurl);
        }else {
            return R.error();
        }
    }

}